<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *
 * @abstract 产品管理
 * @author zxj
 *
 */
class Product extends MY_Controller
{
    private $t_product = 'maintain_product';  //产品表

    function __construct()
    {
        parent::__construct();
        $this->load->model('procurement_model');
        //加载模型
        $this->load->model('product_model');
        $this->load->model('brand_model');
        $this->load->model('fault_model');
        $this->load->model('part_model');
        $this->load->model('fujian_model');
        $this->load->model('material_model');
        $this->load->model('order_model');
        $this->load->model('sort_model');
        $this->load->model('imei_model');
    }

    /**
     * 产品列表
     */
    function index()
    {
        //获取表单数据
        $data = $formField = gp();
        if($data){
            if(!$data['diyKeyword'] && $data['diyValue'])$data['diyKeyword']='sku';
            $formField[$data['diyKeyword']] = $data['diyValue'];
        }
        //默认select设置
        $optSort[$data['sort_id']] = 'selected';
        $data['optSort'] = $optSort;
        $optBrand[$data['brand_id']] = 'selected';
        $data['optBrand'] = $optBrand;
        $optDamage[$data['damage_id']] = 'selected';
        $data['optDamage'] = $optDamage;
        $optKeyword[$data['diyKeyword']] = 'selected';
        $data['optKeyword'] = $optKeyword;

        /**
         * 自定义搜索
         */
        $diySerachFields = array(
            'maintain_id'=>lang('order_wxdh'),'sku'=>'sku','imei'=>'imei','rma'=>'rma',
            'product_model'=>lang('product_cpxh'),'product_name'=>lang('product_cpmc'),'product_quantity'=>lang('product_cpsjl'),
            'is_guarantee'=>lang('product_zbtype'),
            'add_user'=>lang('product_tjr'),'remark_customer'=>lang('product_khbz'),'source_product_id'=>'source_product_id',
            'size'=>'size','color'=>'color','product_id'=>'id'
        );
        $data['diySerachFields']= $diySerachFields;

        /**
         * 搜索逻辑处理
         */
        $where = $whereLike = array();
        //获取表字段(即查询条件,时间查询额外处理)
        $fieldsList = $this->db->list_fields($this->t_product);
        $fieldsList[] = 'startTime';
        $fieldsList[] = 'endTime';

        //需要模糊查询的字段
        $likeAry = array('maintain_id', 'sku', 'imei', 'product_model', 'rma','remark_customer');
        //拼接查询字符串
        $searchStr = 'products/product/index/?';
        foreach ($formField as $key => $val) {
            if ($val==='' || !in_array($key, $fieldsList)) continue;
            $val = trim($val);
            if (in_array($key, $likeAry)) {
                $whereLike[$key] = $val;
            } elseif ($key == 'startTime') {
                $where['add_time >'] = $val;
            } elseif ($key == 'endTime') {
                $where['add_time <'] = $val;
            } else {
                $where[$key] = $val;
            }
            $searchStr .= $key . '=' . $val . '&';
        }
        $searchStr = rtrim($searchStr, '&');
        //分页
        $this->load->library('pagination');
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url($searchStr);
        $config['total_rows'] = $this->product_model->countRows($this->t_product, $where, '', $whereLike);
        $config['per_page'] = $data['outputExcel']?1000:20;
        $config['uri_segment'] = config_item('enable_lang') ? 5 : 4;
        $page = max(1, intval($data['page']));
        $slimit = ($page - 1) * $config['per_page'];
        $this->pagination->initialize($config);
        $data['show_pages'] = $this->pagination->create_links();
        $num_page = ceil($config['total_rows'] / $config['per_page']);
        $data['show_params'] = "总共{$config['total_rows']}条记录   {$config['per_page']}条/页   当前第{$page}/{$num_page}页";
        //查询
        $datalist = $this->product_model->select($this->t_product, $slimit, $config['per_page'], 'add_time desc', $where, '', $whereLike);
        //重构数据
        foreach ($datalist as $key => &$vary) {
            $vary['id'] = $vary['product_id'];
            $sortFirst = $this->sort_model->get_sort($vary['sort_id']);
            $vary['sort_name'] = $sortFirst['sort_name'];
            $brandFirst = $this->brand_model->get_brand($vary['brand_id']);
            $vary['brand_name'] = $brandFirst['brand_name'] ? $brandFirst['brand_name'] : '其他品牌';
            $damageFirst = $this->product_model->get_damage($vary['damage_id']);
            $vary['damage_name'] = $damageFirst['damage_name'] ? $damageFirst['damage_name'] : '/';
            $vary['is_guarantee_name'] = $vary['is_guarantee'] ? 'yes' : 'no';
            if ($this->users['role'] == 'repairer') {
                $vary['edit_url'] = blang_url('products/product/repair_product/' . $vary['id']);
            } elseif ($this->users['role'] == 'service') {
                $vary['edit_url'] = blang_url('products/product/qc_product/' . $vary['id']);
            }
        }
        unset($vary);
        $data['dataList'] = $datalist;
        //导出数据
        $data['outputUrl'] = blang_url($searchStr . '&outputExcel=true&page=' . $data['page']);
        if ($data['outputExcel']) {
            $fieldData = array(
                'maintain_id' => '维修单号', 'product_id' => '产品ID', 'sku' => 'SKU',
                'product_model' => '产品型号', 'imei' => 'IMEI', 'add_time' => '创建时间', 'brand_name' => '品牌',
                'damage_name' => '外观状况', 'add_user' => '添加人', 'guarantee_date' => '质保日期',
                'weixiudan_order_id'=>'退货单号'
            );
            excel_output('产品列表', $fieldData, $datalist);
        } else {
            //获取所有分类
            $sortList = $this->sort_model->get_sort();
            $data['sortList'] = $sortList;
            //获取所有品牌
            $brandList = $this->brand_model->get_brand();
            $data['brandList'] = $brandList;
            //获取所有外观状况
            $damagedList = $this->product_model->get_damage();
            $data['damageList'] = $damagedList;

            //视图以及样式
            $this->load->view('defaults/product_list', $data);
            $this->load->view('defaults/common/footer');
        }
    }


    /**
     * 新增产品
     * @param string maintain_id 维修单ID
     */
    function add($maintain_id = '')
    {
        //表单处理
        $data['post_type'] = __FUNCTION__;
        $productData = gp();//数据保存
        $productData['maintain_id'] = empty($maintain_id) ? gp('maintain_id') : $maintain_id;
        //获取维修订单信息
        $orderFirst = $this->order_model->getOrderData($productData['maintain_id']);
        if(!$orderFirst){
            show_goto('orders/order/','订单不存在，添加产品失败!');
        }
        $data['productFirst'] = $productData;
        //插入数据
        if ($productData['submits'] && $productData['maintain_id']) {
            //创建产品
            $productData['remark_cn'] = $productData['append_remark'];
            $id = $this->product_model->addOrSetProduct($productData);
            //苹果
            $iphoneType = $productData['iphone_xh'];
            if($id && $productData['brand_id']==73 && $iphoneType){
                $icolor = (int)$productData['iphone_ys'];
                $imemory = (int)$productData['iphone_nc'];
                $ilock = (int)$productData['iphone_zw'];
                $sql = 'SELECT * FROM material_group where mg_type=\''.$iphoneType.'\' and (mg_memory='.$imemory.' or mg_memory=0) and (mg_color='.$icolor.' or mg_color=0) and (mg_lock='.$ilock.' or mg_lock=0); ';
                $materialList = $this->common_model->getQuery($sql,'result_array');
                $total_price = 0;
                $orderOutData = array('oid'=>$orderFirst['maintain_id'],'product_model'=>$iphoneType);
                foreach ($materialList as $rs) {
                    $skuMap[] = array(
                        'sku'=>$rs['mg_sku'],
                        'accessory_quantity'=>$productData['product_quantity'],
                        'mg_public'=>$rs['mg_public']
                    );
                }
                $orderOutData['skuMap'] = $skuMap;
                //判断库存
                $pushData = array('account'=>'tomrepair', 'token'=>'tomrepairOrderOut','data'=>json_encode($orderOutData));
                $url = 'http://58.250.165.205:8889/webService/tomrepairOrderOut.php';
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_HEADER, 0);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($pushData));
                $output = curl_exec($ch);
                if(curl_exec($ch) === false)
                {
                    echo 'Curl error: ' . curl_error($ch);
                    exit;
                }
                curl_close($ch);
                $curlOutput = json_decode($output,true);
                if(!$curlOutput['success']){
                    echo '库存不足的SKU有:';
                    print_r($curlOutput['skuNotStockArr']);
                    var_dump($output);
                    show_goto('products/product/add/'.$orderFirst['maintain_id'],$curlOutput['message']);
                }
                foreach ($materialList as $rs) {
                    $total_price += $rs['mg_price']*$rs['mg_number'];
                    $indata = array(
                        'pid'=>$id,'sku'=>$rs['mg_sku'],'accessory_price'=>$rs['mg_price'],
                        'accessory_quantity'=>$rs['mg_number'],'accessory_name'=>$rs['mg_name'],'accessory_currency'=>'RMB',
                        'accessory_cost'=>$rs['mg_price'],'add_user'=>$this->users['account'],'add_time'=>date('Y-m-d H:i:s')
                    );
                    $this->common_model->insert('maintain_accessory',$indata);
                }
                $total_price = $total_price*$productData['product_quantity'];
                //生成报价单
                $indata = array(
                    'pid'=>$id,'oid'=>$productData['maintain_id'],'maintain_price'=>$total_price*0.05,
                    'accessory_price'=>$total_price,'freight_price'=>$orderFirst['freight_price'],
                    'price_sort'=>'RMB','add_time'=>date('Y-m-d H:i:s'),'add_user'=>$this->users['account']

                );
                $this->common_model->insert('maintain_product_price',$indata);
            }
            show_goto('products/product/inDetails/'.$id,'新增产品成功!');
        } else {
            //获取产品类型
            $sortList = $this->sort_model->get_sort();
            $data['sortList'] = $sortList;
            //是否属于苹果
            $data['isApple'] = false;
            //获取所有品牌
            $brandList = $this->brand_model->get_brand();
            $data['brandList'] = $brandList;
            //获取所有外观状况
            $damagedList = $this->product_model->get_damage();
            $data['damageList'] = $damagedList;

            //视图以及样式
            $this->breadcrumb->append_crumb(
                array('url' => 'orders/order/inDetails/'.$maintain_id,
                    'name' => lang('order_fhdqdd'))
            );
            $this->load->view('defaults/product_post', $data);
            $this->load->view('defaults/common/footer');
        }
    }

    /**
     * 修改产品
     * @param string $id
     */
    function edit($id = '')
    {
        //表单处理
        $data['post_type'] = __FUNCTION__;
        //接收数据
        $id = empty($id) ? gp('id') : $id;
        $productFirst = $this->product_model->get_product($id);
        $data['productFirst'] = $productFirst;
        //修改数据
        $productData = gp();
        if ($productData['submits'] && $productData['id']) {
            //更新产品
            $append_remark = trim($productData['append_remark']);
            if($append_remark && $append_remark!=$productFirst['remark_cn']){
                $remark_cn_str = '<div class="append_remark">';
                $remark_cn_str .= 'date:'.date('y-m-d H:i:s').'&nbsp; user:'.$this->users['account'].'&nbsp;  content:'.$append_remark;
                $remark_cn_str .= '</div>';
                $productData['remark_cn'] = $remark_cn_str.$productFirst['remark_cn'];
            }
            $this->product_model->addOrSetProduct($productData, $id);
            show_goto('products/product/inDetails/'.$id,'修改产品成功!');
        }else{
            //获取产品类型
            $sortList = $this->sort_model->get_sort();
            $data['sortList'] = $sortList;
            //是否属于苹果
            $data['isApple'] = $productFirst['brand_id']==73?true:false;
            //获取所有品牌
            $brandList = $this->brand_model->get_brand();
            $data['brandList'] = $brandList;
            //获取所有外观状况
            $damagedList = $this->product_model->get_damage();
            $data['damageList'] = $damagedList;
            //默认选中
            $optSort[$productFirst['sort_id']] = 'selected';
            $data['optSort'] = $optSort;
            $optBrand[$productFirst['brand_id']] = 'selected';
            $data['optBrand'] = $optBrand;
            if ($productFirst['is_guarantee'] !== '') {
                $ckdsfzb[$productFirst['is_guarantee']] = 'checked';
                $data['ckdsfzb'] = $ckdsfzb;
            }
            if ($productFirst['is_description'] !== '') {
                $ckdmssfyz[$productFirst['is_description']] = 'checked';
                $data['ckdmssfyz'] = $ckdmssfyz;
            }
            if ($productFirst['damage_id'] !== '') {
                $ckdwgzk[$productFirst['damage_id']] = 'checked';
                $data['ckdwgzk'] = $ckdwgzk;
            }
            if ($productFirst['is_bluetooth'] !== '') {
                $ckdsfly[$productFirst['is_bluetooth']] = 'checked';
                $data['ckdsfly'] = $ckdsfly;
            }
            if ($productFirst['is_yaokong'] !== '') {
                $ckdsfyk[$productFirst['is_yaokong']] = 'checked';
                $data['ckdsfyk'] = $ckdsfyk;
            }

            //视图以及样式
            $this->breadcrumb->append_crumb(array('url' => 'products/product/edit/'.$id,'name' => lang('public_editText')));
            $this->breadcrumb->append_crumb(
                array('url' => 'products/product/inDetails/'.$id,
                    'name' => lang('product_fhdqcp'))
            );
            $this->breadcrumb->append_crumb(
                array('url' => 'orders/order/inDetails/'.$productFirst['maintain_id'],
                    'name' => lang('order_fhdqdd'))
            );
            $this->breadcrumb->append_crumb(array('url'=>'orders/order/edit/'.$productFirst['maintain_id'], 'name'=>lang('menu_xgdd')));

            $this->load->view('defaults/product_post', $data);
            $this->load->view('defaults/common/footer');
        }

    }


    /**
     * 质检产品
     * @param string $id
     */
    function qc_product($id = ''){
        //表单处理
        $data['post_type'] = __FUNCTION__;
        //接收数据
        $id = empty($id) ? gp('id') : $id;
        $productFirst = $this->product_model->get_product($id);
        if($productFirst['sort_id']==2){
            $productFirst['sort_id']=1;
        }
        //修改数据
        $productData = gp();
        if ($productData['submits'] && $productData['id']) {
            //更新产品
            $append_remark = trim($productData['append_remark']);
            if($append_remark && $append_remark!=$productFirst['remark_cn']){
                $remark_cn_str = '<div class="append_remark">';
                $remark_cn_str .= 'date:'.date('y-m-d H:i:s').'&nbsp; user:'.$this->users['account'].'&nbsp;  content:'.$append_remark;
                $remark_cn_str .= '</div>';
                $productData['remark_cn'] = $remark_cn_str.$productFirst['remark_cn'];
            }
            $wgzkson = array(
                'screen'=>$productData['screen'],
                'front'=>$productData['front'],
                'frame'=>$productData['frame'],
                'back'=>$productData['back']
            );
            $productData['wgzkson'] = serialize($wgzkson);
            $rsRow = $this->product_model->addOrSetProduct($productData,$id);
            if ($rsRow) {
                //先更新附件
                $this->fujian_model->setProductFujian($id, $productData['attachment_id']);

                //更新故障
                $this->fault_model->setProductFault($id, $productData['fault_id']);

                //更新质检报告
                $qcReportData = $this->common_model->addQcReport($id);
                $this->product_model->setQcReport($id, $qcReportData);

            }
            show_goto('products/product/inDetails/'.$id,'修改成功!');
        } else {
            //获取所有外观状况
            $damagedList = $this->product_model->get_damage();
            $data['damageList'] = $damagedList;
            //获取所有附件
            $fujianList = $this->fujian_model->get_fujian('','',$productFirst['sort_id']);
            $data['fujianList'] = $fujianList;
            //获取所有故障
            $guzhangList = $this->fault_model->get_fault('','',$productFirst['sort_id']);
            $data['guzhangList'] = $guzhangList;
            //默认选中
            $optBrand[$productFirst['brand_id']] = 'selected';
            $data['optBrand'] = $optBrand;
            if ($productFirst['is_guarantee'] !== '') {
                $ckdsfzb[$productFirst['is_guarantee']] = 'checked';
                $data['ckdsfzb'] = $ckdsfzb;
            }
            if ($productFirst['is_description'] !== '') {
                $ckdmssfyz[$productFirst['is_description']] = 'checked';
                $data['ckdmssfyz'] = $ckdmssfyz;
            }
            if ($productFirst['damage_id'] !== '') {
                $ckdwgzk[$productFirst['damage_id']] = 'checked';
                $data['ckdwgzk'] = $ckdwgzk;
            }
            if ($productFirst['is_bluetooth'] !== '') {
                $ckdsfly[$productFirst['is_bluetooth']] = 'checked';
                $data['ckdsfly'] = $ckdsfly;
            }
            if ($productFirst['is_yaokong'] !== '') {
                $ckdsfyk[$productFirst['is_yaokong']] = 'checked';
                $data['ckdsfyk'] = $ckdsfyk;
            }
            //附件
            $product_fujian = $this->fujian_model->get_fujian('',$id);
            foreach ($product_fujian as $rs) {
                $ckdfujian[$rs['attachment_id']] = 'checked';
                $data['ckdfujian'] = $ckdfujian;
            }
            //故障
            $product_guzhang = $this->fault_model->get_fault('', $id);
            foreach ($product_guzhang as $rs) {
                $ckdguzhang[$rs['maintain_fault_id']] = 'checked';
                $data['ckdguzhang'] = $ckdguzhang;
            }
            //获取产品类别
            $sortFirst = $this->sort_model->get_sort($productFirst['sort_id']);
            $productFirst['sort_name'] = $sortFirst['sort_name'];

            //获取品牌
            if($productFirst['brand_id']){
                $brandFirst = $this->brand_model->get_brand($productFirst['brand_id']);
                $productFirst['brand_name'] = $brandFirst['brand_name'];
            }

            //外观状况详情
            if($productFirst['wgzkson']){
                $wgzkson = unserialize($productFirst['wgzkson']);
                $productFirst['optscreen'.$wgzkson['screen']] = 'checked';
                $productFirst['optfront'.$wgzkson['front']] = 'checked';
                $productFirst['optframe'.$wgzkson['frame']] = 'checked';
                $productFirst['optback'.$wgzkson['back']] = 'checked';
            }

            //大象品牌保内的品牌
            $dxBrandList = array(
                'P6000PRO','P8000','P7000'/*,'S2','S2PLUS','M1','TRUNK','M2',
                'VOWNEY','E06','P9000','Ivory'*/
            );
            $product_model = strtoupper($productFirst['product_model']);
            if($productFirst['brand_id']==11){
                $data['dxBrandList'] = $dxBrandList;
                /*
                if(in_array($product_model,$dxBrandList)){
                    $ckdsfzb[2] = 'checked';
                    $data['ckdsfzb'] = $ckdsfzb;
                }
                */
                //调取大象接口 354810070190404
                if($productFirst['imei']){
                    $dxApiData = file_get_contents('http://crm.m8cool.com/GetIMEI.ashx?IMEI='.$productFirst['imei']);
                    if($dxApiData && trim($dxApiData)) {
                        $dxApiData = json_decode($dxApiData, true);
                        $dxProduct = $dxApiData['Product'][0];
                        $warrantyStr = '是否质保:' . $dxProduct['IsWarranty'] . ';质保结束日期:' . $dxProduct['WarrantyEnd'];
                        $data['warrantyStr'] = $warrantyStr;
                    }else{
                        $data['warrantyStr'] = '未获取到质保信息,可能不属于质保机';
                    }
                }
            }

            $data['productFirst'] = $productFirst;
            //视图以及样式
            $this->breadcrumb->append_crumb(array('url' => '', 'name' => lang('product_jxzj')));
            $this->breadcrumb->append_crumb(array('url' => 'products/product/edit/'.$id,'name' => lang('public_editText')));
            $this->breadcrumb->append_crumb(
                array('url' => 'products/product/inDetails/'.$id,
                    'name' => lang('product_fhdqcp'))
            );
            $this->breadcrumb->append_crumb(
                array('url' => 'orders/order/inDetails/'.$productFirst['maintain_id'],
                    'name' => lang('order_fhdqdd'))
            );

            $this->load->view('defaults/qc_product', $data);
            $this->load->view('defaults/common/footer');
        }
    }


    /**
     * 维修产品
     * @param string $id
     */
    function repair_product($id = ''){
        //表单处理
        $data['post_type'] = __FUNCTION__;
        //接收数据
        $id = empty($id) ? gp('id') : $id;
        $productFirst = $this->product_model->get_product($id);
        if(!$productFirst){
            show_error('未获取到产品信息');
        }

        if($productFirst['sort_id']==2){
            $productFirst['sort_id']=1;
        }

        //修改数据
        $productData = gp();
        if ($productData['submits']) {
            //更新产品数据
            $this->product_model->addOrSetProduct($productData,$id);

            //更新维修项
            $this->part_model->setProductPart($id, $productData['maintain_part_id']);

            //获取维修项
            $ids = implode(',',$productData['maintain_part_id']);
            $sql = 'select * from maintain_part where maintain_part_id IN('.$ids.')';
            $partAry = $this->product_model->getQuery($sql, 'result_array');
            $partStr = '';
            foreach ($partAry as $pval) {
                $partStr .= $pval['maintain_part_name_en'] . ';';
            }
            //更新报价单 手工费
            $curPriceData = $this->common_model->addPartPrice($id);
            $curPriceData['part'] = rtrim($partStr, ';');
            $this->product_model->setProductPrice($id, $curPriceData);

            show_goto('products/product/inDetails/'.$id,'修改成功');
        } else {
            //签约品牌提示换主板
            $signBrand = $this->product_model->selectFirst('mt_sign_brand',array('bid'=>$productFirst['brand_id']));
            $data['signBrand'] = $signBrand;

            //获取所有维修项
            $partList = $this->part_model->get_part('','',$productFirst['sort_id']);
            $data['partList'] = $partList;
            //checked默认选中
            $product_part = $this->part_model->get_part('', $id);
            foreach ($product_part as $rs) {
                $ckdpart[$rs['maintain_part_id']] = 'checked';
                $data['ckdpart'] = $ckdpart;
            }

            //质保类型
            if ($productFirst['is_guarantee'] !== '') {
                $ckdsfzb[$productFirst['is_guarantee']] = 'checked';
                $data['ckdsfzb'] = $ckdsfzb;
            }

            //获取产品类别
            $sortFirst = $this->sort_model->get_sort($productFirst['sort_id']);
            $productFirst['sort_name'] = $sortFirst['sort_name'];

            //获取外观状况
            $damagedFirst = $this->product_model->get_damage($productFirst['damage_id']);
            $productFirst['damage_name'] = $damagedFirst['damage_name'];

            //获取品牌
            if($productFirst['brand_id']){
                $brandFirst = $this->brand_model->get_brand($productFirst['brand_id']);
                $productFirst['brand_name'] = $brandFirst['brand_name'];
            }

            $data['productFirst'] = $productFirst;
            //视图以及样式
            $this->breadcrumb->append_crumb(array('url' => 'products/product/edit/'.$id, 'name' => lang('menu_xgcp')));
            $this->breadcrumb->append_crumb(
                array('url' => 'products/product/inDetails/'.$id,
                    'name' => lang('product_fhdqcp'))
            );

            $this->breadcrumb->append_crumb(array('url' => 'orders/order/inDetails/'.$productFirst['maintain_id'], 'name' => lang('order_fhdqdd')));

            $this->load->view('defaults/productRepairer_post', $data);
            $this->load->view('defaults/common/footer');
        }
    }


    /**
     * 同意报价
     * @param string $id 产品id
     * @param string $is_accept 是否同意报价
     */
    function accept_price($id = '',$is_accept='null')
    {
        $productFirst = $this->product_model->get_product($id);
        if(!$productFirst){
            js_goto('','非法操作,参数错误',1);
        }
        $oid = $productFirst['maintain_id'];
        $orderFirst = $this->common_model->selectFirst('maintain_order',array('maintain_id'=>$oid));
        if($orderFirst['status_id'] != '4' && MYDEBUG!='true' && $is_accept!='null' && $orderFirst['maintain_type_id']!=8){
            js_goto('','请先修改订单为已报价',1);
        }

        $where = array('pid' => $id);
        $this->common_model->updateset('maintain_product_price', array( 'is_accept_price' => $is_accept), $where);

        if($is_accept==1){
            $sss=$this->procurement_model->ssslele($id);
            if(MYDEBUG=='true'){
                gsh_output($sss,1);
            }
            $idlist=array();
            foreach($sss as $val){
                $idlist[]=$val['id'];
                $this->procurement_model->updatecg($val['id'],array('status'=>2));
            }
            $url="http://stock.dhhtgroup.com/webService/GetPublicInventoryRequirement.php";
            $this->materialpost($url,$idlist);
        }

        show_goto('orders/order/edit/'.$oid,'操作成功!');
    }


    public function materialpost($url,$data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER,true);
        curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_exec($ch);
        curl_close($ch);
    }



    /**
     * 查看产品详情
     * @param string $id
     * @return mixture
     */
    function inDetails($id = '')
    {
        $id = empty($id) ? gp('id') : $id;
        //获取产品信息
        $productFirst = $this->product_model->get_product($id);
        //获取维保时间
        if($productFirst['imei']) {
            $wbtime = $this->imei_model->selectimeitime($productFirst['imei']);
            if ($wbtime) {
                $productFirst['warranty_start_date'] = $wbtime['warranty_start_date'];
                $productFirst['warranty_end_date'] = $wbtime['warranty_end_date'];
            }
        }
        //获取产品类别
        $sortFirst = $this->sort_model->get_sort($productFirst['sort_id']);
        $productFirst['sort_name'] = $sortFirst['sort_name'];
        //获取外观状况
        $damagedFirst = $this->product_model->get_damage($productFirst['damage_id']);
        $productFirst['damage_name'] = $damagedFirst['damage_name'];

        //获取品牌
        if($productFirst['brand_id']){
            $brandFirst = $this->brand_model->get_brand($productFirst['brand_id']);
            $productFirst['brand_name'] = $brandFirst['brand_name'];
        }
        $data['productFirst'] = $productFirst;

        //获取物料
        $wuliaoList = $this->material_model->get_wuliao('', $id);
        $sss=$this->procurement_model->ssslele($id);
        if($sss) {
            foreach ($sss as $row) {
                $sku[] = $row['sku'];
                $status[$row['sku']]=$row['status'];
            }
        }
        foreach($wuliaoList as $val){
            if($sku&&$status) {
                if (in_array($val['sku'],$sku) && $status[$val['sku']]==0) {
                    $caofeini[$val['sku']]='yes';
                }
            }
        }
        $data['caofeini']=$caofeini;
        $data['wuliaoList'] = $wuliaoList;
        //获取质检报告
        $qcReportFirst = $this->product_model->getQcReport($id);
        $data['qcReportFirst'] = $qcReportFirst;
        //获取报价单
        $priceOneFirst = $this->product_model->getPriceOne($id);
        $data['priceOneFirst'] = $priceOneFirst;

        //视图以及样式
        $this->breadcrumb->append_crumb(array('url' => '', 'name' => lang('product_cpxq') ));
        $this->breadcrumb->append_crumb(array('url'=>'orders/order/inDetails/'.$productFirst['maintain_id'], 'name' => lang('order_fhdqdd')));
        $this->breadcrumb->append_crumb(array('url' => 'products/product/edit/'.$id, 'name' => lang('product_bjdqcp')));

        $this->load->view('defaults/product_inDetail', $data);
        $this->load->view('defaults/common/footer');
    }


    /**
     * 配件管理  此方法已经被部分（添加配件）替代 防止报错 方法暂时保留
     * @param string $pid
     * @return string
     */
    function peijian($pid = '',$ordid='')
    {
        $ordid = trim($ordid);
        if(strlen($ordid)==16){
            $newOrder = true;
        }
        //表单处理
        $data['post_type'] = __FUNCTION__;
        $peijianData = gp();//数据保存
        $pid = empty($pid) ? $peijianData['pid'] : intval($pid);
        $peijianData['pid'] = $pid;
        $data['peijianData'] = $peijianData;
        $mtid=$peijianData['wxdh'];
        //获取产品信息
        if($newOrder){
            $productFirst = $this->common_model->selectFirst('mt_product',array('id'=>$pid));
        }else{
            $productFirst = $this->product_model->get_product($pid);
        }
        //插入数据
        if ($peijianData['pid'] && $peijianData['wid']) {
            //获取订单信息
            if($newOrder){
                $orderFirst = $this->common_model->selectFirst('mt_order',array('id'=>$productFirst['oid']));
            }else{
                $orderFirst = $this->order_model->getOrderData($productFirst['maintain_id']);
            }
            //根据订单查询维修站点货币
            if($newOrder){
                $repairSite = $this->common_model->selectFirst('mt_service_center',array('id'=>$orderFirst['service_center']));
            }else{
                $repairSite = $this->order_model->getRepiarSiteData($orderFirst['repair_site_id']);
            }
            //当前维修站点货币种类
            if($newOrder){
                $accessoryCurrency = $repairSite['currency'];
            }else{
                $accessoryCurrency = $repairSite['price_sort'];
            }

            //获取汇率
            $rateRs = $this->common_model->selectFirst('exchange_rate', array('code' => $accessoryCurrency));
            if (!$rateRs) {
                show_error('获取费率失败,新增配件失败!');
            }
            $accessoryPrice = $peijianData['accessory_price'];
            if($orderFirst['source_site_id'] != 8) {
                if ($accessoryCurrency == $peijianData['cucy']) {
                    $accessoryPrice = $peijianData['accessory_price'];
                } else {
                    $accessoryPrice = floatval($peijianData['accessory_price'] / $rateRs['value']);
                }
            }
            $peijianData['accessory_currency'] = $accessoryCurrency;
            $peijianData['accessory_price'] = $accessoryPrice;
            //ADD
            if($newOrder){
                $rsid = $this->common_model->insert('mt_product_parts',$peijianData);
            }else{
                $rsid = $this->material_model->addProductWuliao($peijianData);
            }
            if ($rsid) {
                //减去库存
                $wlkcData = array('quantity' => 'quantity-' . $peijianData['accessory_quantity']);
                $this->common_model->updateset('material_list', $wlkcData, array('id' => $peijianData['wid']));
                //更新报价单物料费用
                $accSum_price = 0;
                $wuliaoList = $this->material_model->get_wuliao('', $pid);
                foreach ($wuliaoList as $rs) {
                    $accSum_price += intval($rs['accessory_quantity']) * floatval($rs['accessory_price']);
                }
                $cpPriceData['accessory_price'] = $accSum_price;
                $cpPriceData['pid'] = $pid;
                $cpPriceData['oid'] = $productFirst['maintain_id'];
                $this->product_model->setProductPrice($pid, $cpPriceData);
            }
            js_goto(blang_url('products/product/peijian/' . $pid.'/'.$mtid));
        } else {
            //获取产品配件
            $wuliaoList = $this->material_model->get_wuliao('',$pid);
            $sss=$this->procurement_model->ssslele($pid);
            if($sss) {
                foreach ($sss as $row) {
                    $idarr[] = $row['id'];
                }
            }
            foreach($wuliaoList as $val){
                if($idarr) {
                    if (in_array($val['pcmid'],$idarr)) {
                        $caofeini[$val['id']]='yes';
                    }
                }
            }
            $data['caofeini']=$caofeini;
            $data['wuliaoList'] = $wuliaoList;
            $data['wuliaoList'] = $wuliaoList;
            $data['mtid']=$ordid;

            if($newOrder){
                $this->breadcrumb->append_crumb(array('url' => 'orders/Order_new/inDetails/'.$productFirst['oid'], 'name' => lang('order_fhdqdd')));
                $this->breadcrumb->append_crumb(array('url'=>'orders/Order_new/edit/'.$productFirst['oid'], 'name'=>lang('menu_xgdd')));
            }else{
                $this->breadcrumb->append_crumb(array('url' => 'orders/order/inDetails/'.$productFirst['maintain_id'], 'name' => lang('order_fhdqdd')));
                $this->breadcrumb->append_crumb(array('url'=>'orders/order/edit/'.$productFirst['maintain_id'], 'name'=>lang('menu_xgdd')));
            }

            $this->load->view('defaults/material', $data);
        }
    }


    /**
     * 配件管理
     * @param string $pid
     * @param string $oid
     */
    function parts($pid = '',$oid='')
    {
        //表单处理
        $data['post_type'] = __FUNCTION__;
        $gpData = gp();//数据保存
        $pid = empty($pid)?$gpData['pid']:intval($pid);
        $data['pid'] = $pid;
        $data['peijianData'] = $gpData;
        //获取产品信息
        $productFirst = $this->common_model->selectFirst('mt_product',array('id'=>$pid));
        //插入数据
        if ($gpData['submits']) {
            $this->breadcrumb->append_crumb(array('url' => 'orders/Order_new/inDetails/'.$productFirst['oid'], 'name' => lang('order_fhdqdd')));
            $this->breadcrumb->append_crumb(array('url'=>'orders/Order_new/edit/'.$productFirst['oid'], 'name'=>lang('menu_xgdd')));
        } else {
            //获取产品配件
            $wuliaoList = $this->material_model->get_wuliao('',$pid);
            $sss=$this->procurement_model->ssslele($pid);
            if($sss) {
                foreach ($sss as $row) {
                    $idarr[] = $row['id'];
                }
            }
            foreach($wuliaoList as $val){
                if($idarr) {
                    if (in_array($val['pcmid'],$idarr)) {
                        $caofeini[$val['id']]='yes';
                    }
                }
            }
            $data['caofeini']=$caofeini;
            $data['wuliaoList'] = $wuliaoList;
            $data['wuliaoList'] = $wuliaoList;
            $data['mtid']=$oid;

            $this->breadcrumb->append_crumb(array('url' => 'orders/Order_new/inDetails/'.$productFirst['oid'], 'name' => lang('order_fhdqdd')));
            $this->breadcrumb->append_crumb(array('url'=>'orders/Order_new/edit/'.$productFirst['oid'], 'name'=>lang('menu_xgdd')));

            $this->load->view('defaults/material', $data);
        }
    }



    /**
     * 删除产品配件
     * @param string $id 产品配件id
     * @param string $pid 产品id
     * @return bool
     */
    function del_peijian($id='',$pid='',$orderId){
        if(!$id) return '';
        $pjFirst = $this->common_model->selectFirst('maintain_accessory',array('id'=>$id));
        //加上库存
        if($pjFirst){
            $wlkcData = array('quantity'=>'quantity+'.$pjFirst['accessory_quantity']);
            $this->common_model->updateset('material_list',$wlkcData,array('id'=>$pjFirst['wid']));
            $this->material_model->del_wuliao($id);
            //更新报价单物料费用
            $accSum_price = '0';
            $wuliaoList = $this->material_model->get_wuliao('', $pid);
            foreach ($wuliaoList as $rs) {
                $accSum_price += intval($rs['accessory_quantity'])*floatval($rs['accessory_price']);
            }
            $cpPriceData['accessory_price'] = $accSum_price;
            $this->product_model->setProductPrice($pid,$cpPriceData);
        }
        if(MYDEBUG!='true'){
            redirect(blang_url('products/product/peijian/'.$pid.'/'.$orderId));
        }
    }



    /**
     * 删除产品
     * @param string $id
     * @param string $page
     */
    function del($id = '',$page = ''){
        $roleAry = array('zlj','zlj2','admin','prezwang','Julie','anna');
        if(!$id || !in_array($this->users['account'],$roleAry)){
            //show_goto('products/product/','你没有权限这么做');
        }
        $this->product_model->deleteData($id);
        redirect(blang_url('products/product/index/?page='.intval($page)));
    }


}
